package com.study.connect.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.List;

/**
 * byte转serviceInvoke对象DECODE编码（客户端请求对象解码）
 */
@Slf4j
public class ByteToServiceInvokeDecoderHandler extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        /*读取长度，然后再读取内容*/
        byte[] array = new byte[byteBuf.readableBytes()];
        try {
            byteBuf.readBytes(array);
        } finally {
            byteBuf.skipBytes(byteBuf.readableBytes());
        }

        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(array);
             ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);) {
            Object object = objectInputStream.readObject();
            list.add(object);
        } catch (Exception e) {
            log.error("对象流读取异常：{}", e);
        }
    }
}
